package com.hdl.controller;

import com.hdl.constants.Constants;
import com.hdl.pojo.Resume;
import com.hdl.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;

/**
 * 类名 ResumeController
 * 描述 TODO
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/5/16 13:58
 */
@Controller
@RequestMapping("/resume")
public class ResumeController {
    @Autowired
    private ResumeService resumeService;

    @RequestMapping("/list")
    public String list(Model model, HttpSession session){
        Object username = session.getAttribute(Constants.USER_SESSION_KEY);
        final List<Resume> resumes = resumeService.findAll();
        model.addAttribute("resumes", resumes);
        model.addAttribute("username", username);
        return "resume/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String toSave() throws Exception {
        return "/resume/add";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String toEdit(Model model, @PathVariable("id") Long id) throws Exception {
        Optional<Resume> resume = resumeService.findById(id);
        model.addAttribute("resume", resume.get());
        return "/resume/edit";
    }


    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Resume resume) throws Exception {
        checkSaveResumeParam(resume);
        resumeService.save(resume);
        return "redirect:/resume/list";
    }


    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable("id") Long id) throws Exception {
        resumeService.deleteById(id);
        return "redirect:/resume/list";
    }

    private void checkSaveResumeParam(Resume resume) throws Exception {
        if (resume == null){
            throw new Exception("简历不能为空");
        }

        if (resume.getName() == null){
            throw new Exception("简历名称为空");
        }
        if (resume.getPhone() == null){
            throw new Exception("简历电话为空");
        }
    }
}
